//
//  MQSearchDisplayController.swift
//  MQCRM
//
//  Created by 许博 on 2017/5/5.
//  Copyright © 2017年 mechat. All rights reserved.
//

import UIKit

class MQSearchDisplayController: MQBaseViewController {
    
    weak var fromController :MQBaseViewController?
    var configModel:MQToggleConfigModel?
    
    // 假数据
    var dataList : [MQLeadListViewModel]?
    // 搜索历史关键字
    fileprivate var searchHistories : [String]?
    // 历史记录 tableview
    fileprivate var historyTableView:UITableView?
    // 综合 tableview
    fileprivate var complexTableView:UITableView?
    
    // MARK: Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.backgroundGrey
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 去除导航栏分割线
        navigationController?.navigationBar.shadowImage = UIImage()
        navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 恢复导航栏分割线
        navigationController?.navigationBar.shadowImage = nil
        navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
    }

    deinit {
        print("deinit")
    }
    
    // MARK:SetupUI
    private func setupUI(){
        
        searchHistories = loadHistories()  // 读取历史记录
        navigationItem.titleView = searchBar
        searchBar.delegate = self
        searchBar.becomeFirstResponder()
        
        
        setupToggleView()
    }
    
    private func setupToggleView(){
        let toggle = MQToggleView()
        toggle.frame = CGRect(x: 0, y: 0, width: KScreenW, height: KScreenH - 64)
        let config = MQToggleConfigModel()
        config.titleArray = ["综合","销售线索","客户","联系人","销售机会"]
        config.animated = false
        config.titleColorNormal = UIColor(white: 255.0, alpha: 0.7)
        config.titleColorSelected = UIColor.white
        config.titleBackColor = UIColor.clearBlue
        config.indicatorColor = UIColor.color(r: 76, g: 217, b: 100)
        config.subs = setupTableView(count:config.arrCount)
        toggle.configModel = config
        configModel = config
        view.addSubview(toggle)
    }
    
    // 初始化搜索tableview
    private func setupTableView(count:Int)->([UIView]) {
        var subs = [UIView]()
        let rect = CGRect(x: 0, y: 0, width: KScreenW, height: KScreenH - 104)
        
        // 历史记录 tableView
        let historyTB = UITableView(frame: rect, style: .plain)
        self.historyTableView = historyTB
        historyTB.dataSource = self
        historyTB.delegate = self
        historyTB.register(MQSearchHistoryCell.self, forCellReuseIdentifier: "MQSearchHistoryCell")
        historyTB.rowHeight = 44
        historyTB.tag = count + 1
        historyTB.backgroundColor = UIColor.backgroundGrey
        let cleanbtn = cleanBtn
        cleanbtn.frame = CGRect(x: 0, y: 0, width: KScreenW, height: 44)
        historyTB.tableFooterView = cleanbtn
        subs.append(historyTB)
        
        // 综合 tableView
        let complexTB = UITableView(frame: rect, style: .plain)
        complexTableView = complexTB
        complexTB.isHidden = true
        complexTB.dataSource = self
        complexTB.delegate = self
        complexTB.register(MQLeadListCell.self, forCellReuseIdentifier: "MQLeadListCell")
        complexTB.rowHeight = 64
        complexTB.tag = count
        complexTB.backgroundColor = UIColor.backgroundGrey
        subs.append(complexTB)
        // 其他
        for i in 0..<count - 1 {
            let rect = rect.offsetBy(dx: CGFloat((i+1))*KScreenW, dy: 0)
            let conmmonTB = UITableView(frame: rect, style: .plain)
            conmmonTB.rowHeight = 64
            conmmonTB.dataSource = self
            conmmonTB.delegate = self
            conmmonTB.register(MQLeadListCell.self, forCellReuseIdentifier: "MQLeadListCell")
            conmmonTB.tag = i
            conmmonTB.backgroundColor = UIColor.backgroundGrey
            conmmonTB.tableFooterView = createFooter()
            subs.append(conmmonTB)
        }
        return subs
    }

    // MARK: Actions
    // 查询更多
    @objc func moreLeads(){
        print(#function)
    }
    
    // 清空历史记录
    @objc func cleanHistory(){
        print(#function)
        searchHistories?.removeAll()
        historyTableView?.reloadData()
        // 数据库更新存储
        UserDefaults.standard.set(searchHistories, forKey: "SearchHistory")
        UserDefaults.standard.synchronize()
        cleanBtn.isHidden = true
        
    }
    
    public func showInViewController(controller:MQBaseViewController){
        fromController = controller
        controller.navigationController?.setNavigationBarHidden(true, animated: false)
        
    }
    
    // MARK: Lazy Load
    
    private func  createFooter()->(UIView){
        let foot = UIView()
        foot.backgroundColor = UIColor.white
        foot.frame = CGRect(x: 0, y: 0, width: KScreenW, height: 40)
        let searchIcon = UIImageView(frame: CGRect(x: KCommonCellPadding, y: 8, width: 24, height: 24))
        searchIcon.image = UIImage(named: "icMagnifierBlue")
        foot.addSubview(searchIcon)
        let lb = UILabel(frame: CGRect(x: searchIcon.frame.maxX + 10, y: 10, width: 120, height: 20))
        lb.text = "查看更多线索"
        lb.font = UIFont.systemFont(ofSize: 14)
        lb.textColor = UIColor.clearBlue
        foot.addSubview(lb)
        let indicator = UIImageView(frame: CGRect(x: KScreenW - 14 - 15, y: (40-14)/2, width: 14, height: 14))
        indicator.image = UIImage(named: "btnGlyphsChevron")
        foot.addSubview(indicator)
        
        let headLine = UIView()
        headLine.backgroundColor = UIColor.separatorGrey
        headLine.frame = CGRect(x: 20, y: 0, width: KScreenW - 20, height: 0.5)
        foot.addSubview(headLine)
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(moreLeads))
        foot.addGestureRecognizer(tap)
        return foot
    }
   
    
    fileprivate lazy var cleanBtn : UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("清除历史记录", for: .normal)
        btn.setTitleColor(UIColor.clearBlue, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.addTarget(self, action: #selector(cleanHistory), for: .touchUpInside)
        btn.backgroundColor = UIColor.white
        let line = UIView()
        line.backgroundColor = UIColor.separatorGrey
        line.frame = CGRect(x: 20, y: 0, width: KScreenW - 20, height: 0.5)
        btn.addSubview(line)

        return btn
    }()
    
    fileprivate lazy var searchBar: MQSearchBar = {
        let searchBar = MQSearchBar()
        searchBar.frame = CGRect(x: 0, y: 20, width: KScreenW, height: 44)
        return searchBar
    }()
    
    
}


// MARK:UISearchBarDelegate
extension MQSearchDisplayController:UISearchBarDelegate {
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        fromController?.navigationController?.setNavigationBarHidden(false, animated: false)
        self.navigationController?.view.removeFromSuperview()
        
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        
        
        
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        if searchBar.text != nil && searchBar.text != "" {
            saveHistory(keyWord: searchBar.text!)
            searchBar.text = ""
            searchBar.resignFirstResponder()
            // 解决取消按钮不能解决的问题
            let cancelBtn = searchBar.value(forKey: "cancelButton") as? UIButton
            cancelBtn?.isEnabled = true
            historyTableView?.reloadData()
            historyTableView?.isHidden = true
            complexTableView?.isHidden = false
            
        }
    }
    
    // FIXME: 数据库存储历史记录
    private func saveHistory (keyWord:String){
        guard let arr = searchHistories else {
            return
        }
        // 重复的不存储
        for k in arr {
            if k == keyWord {
                return
            }
        }
        // 只能存储5个
        let count = searchHistories?.count ?? 0
        cleanBtn.isHidden =  count > 0 ? false : true
        if count >= 5 {
            searchHistories?.removeLast()
        }
        let key = searchBar.text!
        searchHistories?.insert(key, at: 0)
        UserDefaults.standard.set(searchHistories, forKey: "SearchHistory")
        UserDefaults.standard.synchronize()
    }
    
    // FIXME: 读取历史记录
    fileprivate func loadHistories()->([String]){
        let histories = UserDefaults.standard.object(forKey: "SearchHistory")
        guard let newHistories = histories as? [String]
            else {
            return [String]()
        }
        cleanBtn.isHidden =  newHistories.count > 0 ? false : true
        return newHistories
    }
    
}


// MARK:UITableViewDelegate;UITableViewDataSource
extension MQSearchDisplayController:UITableViewDataSource ,UITableViewDelegate{
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        guard let configModel = configModel  else {
            return 0
        }
        
        // 综合
        if tableView.tag == configModel.arrCount {
            return configModel.arrCount - 1
        }
        // 其他
        return 1
    }
    
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        //  综合
        if tableView.tag == configModel?.arrCount {
            let header = view as! UITableViewHeaderFooterView
            header.textLabel?.textColor = UIColor.steelGrey
            header.textLabel?.font = UIFont.systemFont(ofSize: 16)
        }
    }
    
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        //  综合
        if tableView.tag == configModel?.arrCount {
            guard let configModel = configModel else {
                return ""
            }
            return configModel.titleArray?[section + 1]
        }
        return ""
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard let configModel = configModel  else {
            return 0
        }
        //  历史
        if tableView.tag == configModel.arrCount + 1{
            guard let searchHistories = searchHistories else {
                return 0
            }
            return searchHistories.count
        }
        //  综合
//        if tableView.tag == configModel.arrCount{
//            
//        }
        guard let dataList = dataList else {
            return 0
        }
        
        return dataList.count
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        guard let configModel = configModel else {
            return UITableViewCell()
        }
        
        //  历史
        if tableView.tag == configModel.arrCount + 1{
            let cell = tableView.dequeueReusableCell(withIdentifier: "MQSearchHistoryCell", for: indexPath) as! MQSearchHistoryCell
            cell.delegate = self
            cell.title = searchHistories?[indexPath.row]
            return cell
            
        }
        
        // 其他
        let cell = tableView.dequeueReusableCell(withIdentifier: "MQLeadListCell", for: indexPath) as! MQLeadListCell
        cell.viewModel = dataList?[indexPath.row]
        return cell

      
    }
    
}
// MARK: SearchHistoryDeleteSingleDeletge 删除单条记录
extension MQSearchDisplayController:SearchHistoryDeleteSingleDeletge {
    // FIXME:数据库删除
    func deleteSingeData(data:String) {
        // 删除、刷新table
        guard let index = searchHistories?.index(of: data)else {
            return
        }
        
        searchHistories?.remove(at: index)
        historyTableView?.reloadData()
        // 数据库更新存储
        UserDefaults.standard.set(searchHistories, forKey: "SearchHistory")
        UserDefaults.standard.synchronize()
        
    }
}

// MARK:UIScrollViewDelegate - searchBar 滚动时注销第一响应者
extension MQSearchDisplayController:UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        searchBar.resignFirstResponder()
    }
}
